package ferus.tigris.livewallpapers.mechanism;

import java.util.ArrayList;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;

public class Gear implements IGear {
	IGearImagesFactory imagesPool = null;
	float angle = 0;
	Paint paint = new Paint();
	Point position = new Point();
	private ArrayList<IGear> observers = new ArrayList<IGear>();
	private float radius = 10;
	Bitmap image;
	Bitmap speck;
	Bitmap shadow;
	

	public Gear(IGearImagesFactory instance) {
		imagesPool = instance;
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		paint.setDither(true);
		
		image = imagesPool.getGear();
		speck = imagesPool.getGearSpeck();
		shadow = imagesPool.getGearShadow();
		
		radius = (float)(image.getWidth()/2.0);
	}

	@Override
	public void update() {
		float rotate = (float)1.0;
		tick(rotate, radius);
	}

	@Override
	public void interactWith(IGear gear) {
		gear.addObserver(this);
	}

	@Override
	public void addObserver(IGear gear) {
		observers.add(gear);
	}

	@Override
	public void tick(float rotate, float radius) {
		float delta = rotate*radius/this.radius;
		for(IGear gear: observers) {
			gear.tick(-delta, this.radius);
		}
		
		angle += delta;
		
	}

	@Override
	public void setPosition(Point p) {
		position.set((int)(p.x - radius), (int)(p.y - radius));
	}

	@Override
	public float radius() {
		return radius;
	}

	@Override
	public void drawBackground(Canvas c) {
		Bitmap targetGear = getRotatedImage(shadow);
		c.drawBitmap(targetGear, position.x - 5, position.y + 5, paint);
	}

	@Override
	public void draw(Canvas c) {
		Bitmap targetGear = getRotatedImage(image);
		c.drawBitmap(targetGear, position.x, position.y, paint);
		c.drawBitmap(speck, position.x, position.y, paint);
	}

	protected Bitmap getRotatedImage(Bitmap image) {
		Bitmap targetGear = Bitmap.createBitmap(image.getWidth(), image.getHeight(), Bitmap.Config.ARGB_8888 );
		Canvas canvasForGear = new Canvas(targetGear);
		Matrix rotateMatrix = new Matrix();
		rotateMatrix.postRotate(angle, (float) (image.getWidth()/2.0), (float)(image.getHeight()/2.0));
		canvasForGear.drawBitmap(image, rotateMatrix, paint);
		return targetGear;
	}

	public void drawForeground(Canvas c) {
	}

}
